﻿using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Chatu.MsbuildTasks
{
    public class VersioningTask : Task
    {
        #region Fields

        private string _path;
        private int _major = 1;
        private int _minor = 0;
        private int _build = 0;
        private int _revision;
        private string _version;

        #endregion

        #region Properties

        [Required]
        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }

        public int Major
        {
            get { return _major; }
            set { _major = value; }
        }

        public int Minor
        {
            get { return _minor; }
            set { _minor = value; }
        }

        [Required]
        public int Revision
        {
            get { return _revision; }
            set { _revision = value; }
        }

        [Output]
        public string Version
        {
            get { return _version; }
        }

        #endregion

        #region Methods

        public override bool Execute()
        {
            bool toReturn = true;
            
            try
            {
                IncrementBuild();
            }
            catch(Exception e)
            {
                Log.LogErrorFromException(e);
                toReturn = false;
            }

            return toReturn;
        }

        private void IncrementBuild()
        {
            if (File.Exists(_path))
            {
                string previousVersion = File.ReadAllText(_path);
                string[] previousNumbers = previousVersion.Split('.');

                if (previousNumbers.Length == 4) //valid version
                {
                    if (_revision.ToString() == previousNumbers[2])
                        _build = int.Parse(previousNumbers[3]) + 1;
                }
                else
                    Log.LogWarning("File [{0}] contains an invalid version.", _path);
            }
            else
                Log.LogWarning("File [{0}] could not be found.", _path);

            System.Version v = new System.Version(_major, _minor, _revision, _build);
            _version = v.ToString();

            File.WriteAllText(_path, _version);
        }

        #endregion
    }
}
